import { defineStore } from 'pinia'
import { createMenus, createRoutes, generateCacheRoutes } from './helper'
import { local } from '@/utils'
import { router } from '@/router'
import { fetchUserRoutes } from '@/service'
import { staticRoutes } from '@/router/routes.static'
import { useAuthStore } from '@/stores'

export const useRouteStore = defineStore('route-store', {
  state: () => {
    return {
      isInitAuthRoute: false,
      activeMenu: null,
      menus: [],
      rowRoutes: [],
      cacheRoutes: []
    }
  },
  actions: {
    resetRouteStore() {
      this.resetRoutes()
      this.$reset()
    },
    resetRoutes() {
      if (router.hasRoute('appRoot')) router.removeRoute('appRoot')
    },
    // 设置当前高亮的菜单键
    setActiveMenu(key) {
      this.activeMenu = key
    },
    async initRouteInfo() {
      const authStore = useAuthStore()
      if (import.meta.env.VITE_AUTH_ROUTE_MODE === 'dynamic') {
        const userInfo = local.get('userInfo')
        if (!userInfo || !userInfo.role_id) {
          authStore.logout()
          return
        }
        const { data } = await fetchUserRoutes(userInfo.role_id)
        if (data && data.name === 'TokenExpiredError') {
          authStore.logout()
          router.push('/login')
          return null
        }
        return data || null
      } else {
        this.rowRoutes = staticRoutes
        return staticRoutes
      }
    },
    async initAuthRoute() {
      this.isInitAuthRoute = false
      const rowRoutes = await this.initRouteInfo()
      if (!rowRoutes) return window.$message.error('获取路由失败')
      this.rowRoutes = rowRoutes
      // 生成实际的路由并插入
      const routes = createRoutes(rowRoutes)
      router.addRoute(routes)
      // 生成边菜单
      this.menus = createMenus(rowRoutes)
      // 生成路由缓存
      this.cacheRoutes = generateCacheRoutes(rowRoutes)
      this.isInitAuthRoute = true
    }
  }
})
